package cn.ug.product.web.controller;


import cn.ug.account.bean.DataDictionaryBean;
import cn.ug.bean.LoginBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.core.ensure.Ensure;
import cn.ug.core.login.LoginHelper;
import cn.ug.feign.DataDictionaryService;
import cn.ug.feign.ProductOrderService;
import cn.ug.msg.bean.type.SmsType;
import cn.ug.msg.mq.Sms;
import cn.ug.product.bean.request.ProductAuditParamBean;
import cn.ug.product.bean.request.ProductParamBean;
import cn.ug.product.bean.response.ProductBean;
import cn.ug.product.bean.response.ProductFindBean;
import cn.ug.product.bean.response.ProductManageBean;
import cn.ug.product.bean.response.ProductSubtractBean;
import cn.ug.product.bean.status.CommonConstants;
import cn.ug.product.service.ProductService;
import cn.ug.util.UF;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ug.config.QueueName.QUEUE_MSG_SMS_SEND;
import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 * 产品服务
 *
 * @author ywl
 * @date 2018/1/19
 */
@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductOrderService productOrderService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Resource
    private Config config;

    /**
     * 查询发布列表(后台)
     *
     * @param accessToken      登录成功后分配的Key
     * @param productParamBean 请求参数
     * @return 分页数据
     */
    @RequestMapping(value = "queryPublishList", method = GET)
    public SerializeObject<DataTable<ProductManageBean>> queryPublishList(@RequestHeader String accessToken, ProductParamBean productParamBean) {
        if (productParamBean.getPageSize() <= 0) {
            productParamBean.setPageSize(config.getPageSize());
        }

        LoginBean loginBean = LoginHelper.getLoginBean();
        Ensure.that(loginBean == null).isTrue("15000000");
        productParamBean.setCreateUserId(loginBean.getId());
        DataTable<ProductManageBean> dataTable = productService.query(productParamBean);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 查询审核列表(后台)
     *
     * @param accessToken      登录成功后分配的Key
     * @param productParamBean 请求参数
     * @return 分页数据
     */
    @RequestMapping(value = "queryAuditList/{id}", method = GET)
    public SerializeObject<DataTable<ProductManageBean>> queryAuditList(@RequestHeader String accessToken, @PathVariable Integer id, ProductParamBean productParamBean) {
        //验证参数是否正确
        Ensure.that(id).isNull("15000001");
        Ensure.that(CommonConstants.ProductAuditStatus.getName(id)).isNull("00000002");
        productParamBean.setQueryAudit(id);

        LoginBean loginBean = LoginHelper.getLoginBean();
        Ensure.that(loginBean == null).isTrue("15000000");
        if (id == 2) productParamBean.setAuditUserId(loginBean.getId());

        if (productParamBean.getPageSize() <= 0) {
            productParamBean.setPageSize(config.getPageSize());
        }
        DataTable<ProductManageBean> dataTable = productService.query(productParamBean);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 查询产品列表(后台)
     *
     * @param accessToken      登录成功后分配的Key
     * @param productParamBean 请求参数
     * @return 分页数据
     */
    @RequestMapping(value = "queryProductList/{id}", method = GET)
    public SerializeObject<DataTable<ProductManageBean>> queryProductList(@RequestHeader String accessToken, @PathVariable Integer id, ProductParamBean productParamBean) {
        //验证参数是否正确
        Ensure.that(id).isNull("15000001");
        Ensure.that(CommonConstants.ProductSaleStatus.getName(id)).isNull("00000002");
        productParamBean.setQueryProduct(id);
        if (productParamBean.getPageSize() <= 0) {
            productParamBean.setPageSize(config.getPageSize());
        }
        DataTable<ProductManageBean> dataTable = productService.query(productParamBean);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 根据ID查找信息(后台)
     *
     * @param id ID
     * @return 记录集
     */
    @RequestMapping(value = "queryProductById", method = GET)
    public SerializeObject queryProductById(String id) {
        if (StringUtils.isBlank(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000002");
        }
        ProductFindBean entity = productService.queryProductById(id);
        if (null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObject(ResultType.NORMAL, "00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    /**
     * 新增产品(后台)
     *
     * @param accessToken 登录成功后分配的Key
     * @param entity      记录集
     * @return 是否操作成功
     */
    @RequestMapping(method = POST)
    public SerializeObject save(@RequestHeader String accessToken, ProductBean entity) {
        //productService.save(entity);
        productService.productSave(entity);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 修改产品
     *
     * @param accessToken
     * @param entity
     * @return
     */
    @RequestMapping(value = "/update", method = POST)
    public SerializeObject update(@RequestHeader String accessToken, ProductBean entity) {
        productService.productUpdate(entity);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 产品审核
     *
     * @param accessToken           登录成功后分配的Key
     * @param productAuditParamBean ID数组
     * @return 是否操作成功
     */
    @RequestMapping(value = "updateAuditStatus", method = PUT)
    public SerializeObject updateAuditStatus(@RequestHeader String accessToken, ProductAuditParamBean productAuditParamBean) {
        return productService.updateAuditStatus(productAuditParamBean);
        //return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 热销产品(后台)
     *
     * @param accessToken 登录成功后分配的Key
     * @param id          ID数组
     * @param isHot       热销产品状态   1:否 2:是
     * @return 是否操作成功
     */
    @RequestMapping(value = "updateIsHot", method = PUT)
    public SerializeObject updateIsHot(@RequestHeader String accessToken, String[] id, int isHot) {
        if (isHot == 2 && id.length > 2) {
            return new SerializeObject(ResultType.NORMAL, "15000060");
        }
        productService.updateIsHot(id, isHot);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 产品上下架(后台)
     *
     * @param accessToken 登录成功后分配的Key
     * @param id          ID数组
     * @param shelfState  上架状态   1:是 2:否
     * @return 是否操作成功
     */
    @RequestMapping(value = "updateShelfState", method = PUT)
    public SerializeObject updateShelfState(@RequestHeader String accessToken, String[] id, int shelfState) {
        int num = productService.updateShelfState(id, shelfState);
        if (num > 0 && shelfState == 2) {
            SerializeObject<List<DataDictionaryBean>> beans = dataDictionaryService.findListByClassification(cn.ug.msg.bean.status.CommonConstants.MsgType.PRODUCT_DOWN_SHELF.getName(), 1);
            if (beans != null && beans.getData() != null) {
                if (id != null && id.length > 0) {
                    for (String productId : id) {
                        ProductBean product = productService.findById(productId);
                        if (product == null) {
                            continue;
                        }
                        List<DataDictionaryBean> data = beans.getData();
                        if (data != null && data.size() > 0) {
                            for (DataDictionaryBean bean : data) {
                                Sms sms = new Sms();
                                sms.setPhone(bean.getItemValue());
                                sms.setType(SmsType.MANUALLY_OPERATION);
                                Map<String, String> paramMap = new HashMap<>(2);
                                paramMap.put("produtName", product.getName());
                                paramMap.put("hour", String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));
                                sms.setParamMap(paramMap);
                                amqpTemplate.convertAndSend(QUEUE_MSG_SMS_SEND, sms);
                            }
                        }
                    }
                }
            }
        }
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    @RequestMapping(value = "shelf/state", method = POST)
    public SerializeObject updateShelfState(String id, int shelfState) {
        String[] ids = {id};
        productService.updateShelfState(ids, shelfState);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 开启交易(后台)
     *
     * @param accessToken 登录成功后分配的Key
     * @param id          ID数组
     * @param isOpen      是否开启交易   1:是 2:否
     * @return 是否操作成功
     */
    @RequestMapping(value = "updateIsOpen", method = PUT)
    public SerializeObject updateIsOpen(@RequestHeader String accessToken, String id, int isOpen) {
        productService.updateIsOpen(id, isOpen);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 查询是否可以交易(后台)
     *
     * @param productId 产品id
     * @return 是否操作成功
     */
    @RequestMapping(value = "findIsBuy", method = GET)
    public SerializeObject findIsBuy(String productId) {
        productService.findIsBuy(productId);
        //获取待支付新手产品
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 查询是否可以交易(后台)
     *
     * @return 是否操作成功
     */
    @RequestMapping(value = "findIsSell", method = GET)
    public SerializeObject findIsSell() {
        productService.findIsSell();
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 购买产品后增加已募集克数
     *
     * @return 是否操作成功
     */
    @RequestMapping(value = "addToRaiseGram", method = PUT)
    public SerializeObject addToRaiseGram(String productId, BigDecimal gram) {
        productService.addToRaiseGram(productId, gram);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 查询活动任务产品(后台)
     *
     * @return 是否操作成功
     */
    @RequestMapping(value = "findActivityTaskProduct", method = GET)
    public SerializeObject<ProductFindBean> findActivityTaskProduct() {
        ProductFindBean entity = productService.findActivityTaskProduct();
        return new SerializeObject(ResultType.NORMAL, "00000001", entity);
    }

    /**
     * 修改库存数量(后台)
     *
     * @param productId
     * @param stock
     * @return
     */
    @RequestMapping(value = "updateStock", method = POST)
    public SerializeObject updateStock(String productId, Integer stock) {
        Ensure.that(stock).isNull("00000002");
        Ensure.that(productId).isNull("00000002");
        productService.updateStock(productId, stock);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 创建实物金货号
     *
     * @return
     */
    @RequestMapping(value = "create/itemNo", method = GET)
    public SerializeObject createItemNo() {
        return new SerializeObject(ResultType.NORMAL, "00000001", UF.getRandomUUID().toUpperCase());
    }

    /**
     * 根据产品id查询协议内容
     *
     * @param productId
     * @param type
     * @return
     */
    @RequestMapping(value = "find/protocol", method = GET)
    public SerializeObject findProtocol(String productId, Integer type) {
        Ensure.that(productId).isNull("00000002");
        Ensure.that(type).isNull("00000002");
        return new SerializeObject(ResultType.NORMAL, productService.findProtocol(productId, type));
    }

    /**
     * 查询在售的产品列表-根据产品类型
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "find/online/list", method = GET)
    public SerializeObject<List<ProductBean>> queryOnlineList(Integer type) {
        Ensure.that(type).isNull("00000002");
        return new SerializeObject(ResultType.NORMAL, productService.queryOnlineList(type));
    }


    /**
     * 保存折扣金在售期间邀请记录
     *
     * @param friendId
     * @param memberId
     * @return
     */
    @RequestMapping(value = "save/invite/Record", method = POST)
    SerializeObject saveProductInviteRecord(String friendId, String memberId) {
        return new SerializeObject(ResultType.NORMAL, productService.saveProductInviteRecord(friendId, memberId));
    }


    /**
     * 查询会员购买的产品邀请立减详情
     *
     * @param memberId  会员id
     * @param productId 产品id
     * @return
     */
    @RequestMapping(value = "queryMemberIdSubtractNum", method = GET)
    SerializeObject<ProductSubtractBean> queryMemberIdSubtractNum(String memberId, String productId) {
        return new SerializeObject<>(ResultType.NORMAL, productService.queryProductSubtractInfo(memberId, null, productId));
    }

    /**
     * 会员立减次数修改
     *
     * @param memberId
     * @param productId
     * @param type      操作类型： 1减  2加
     * @return
     */
    @RequestMapping(value = "member/subtract/num/update", method = POST)
    SerializeObject memberSubtractNumUpdate(String memberId, String productId, Integer type) {
        return new SerializeObject(ResultType.NORMAL, productService.memberSubtractNumUpdate(memberId, productId, type));
    }

    /**
     * 查询所有的活动产品
     *
     * @return
     */
    @RequestMapping(value = "find/activity/list", method = GET)
    SerializeObject findActivityProductList() {
        return new SerializeObject(ResultType.NORMAL, productService.findActivityProductList());
    }

}
